﻿using HandyControl.Controls;
using MyHelper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using IWshRuntimeLibrary;
using System.Security.Cryptography.X509Certificates;
using SpeechLib;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Shell;
using File = System.IO.File;
using clf.weighing.entity;
using MessageBox = HandyControl.Controls.MessageBox;
using Image = System.Windows.Controls.Image;
using System.Printing;
using System.Diagnostics;
using Microsoft.Office.Interop.Excel;

namespace weighing
{
    public class CommonFunction
    {


        internal static void UpdateDecuationList(object des)
        {
            if (des != null && !String.IsNullOrEmpty(des.ToString()))
            {
                var itemSource = GlobalData.GetAllItemSource();
                string key = "DecuationItemSource";
                string val = des?.ToString() ?? "";
                if (val.IsNullOrEmpty()) return;
                if (itemSource.Keys.Contains(key))
                {
                    var list = itemSource[key];
                    if (!list.Contains(val))
                    {
                        list.Add(val);
                        itemSource[key] = list;
                    }
                }
                else
                {
                    itemSource.Add(key, new List<string>() { val });
                }
            }
        }

        internal static void SetDecuationItemSource(System.Windows.Controls.ComboBox comboBox)
        {
            string key = "DecuationItemSource";
            var itemSource = GlobalData.GetAllItemSource();
            if (itemSource == null || comboBox == null) return;
            if (itemSource.Keys.Contains(key))
            {
                var list = itemSource[key];
                if (list == null)
                {
                    list = new List<string>() {
                        LangHelper.Get(LangKeyNames.DetainingWater),
                        LangHelper.Get(LangKeyNames.DetainingSundries)
                    };
                }
                else
                {
                    if (!list.Contains(LangHelper.Get(LangKeyNames.DetainingWater)))
                    {
                        list.Add(LangHelper.Get(LangKeyNames.DetainingWater));
                    }
                    if (!list.Contains(LangHelper.Get(LangKeyNames.DetainingSundries)))
                    {
                        list.Add(LangHelper.Get(LangKeyNames.DetainingSundries));
                    }
                }
                comboBox.ItemsSource = null;
                comboBox.ItemsSource = list;
            }
        }


        internal static void UpdateInputReamak(object remark)
        {
            if (remark != null && !String.IsNullOrEmpty(remark.ToString()))
            {
                var itemSource = GlobalData.GetAllItemSource();
                string key = "InputReamak";
                string val = remark?.ToString() ?? "";
                if (val.IsNullOrEmpty()) return;
                if (itemSource.Keys.Contains(key))
                {
                    var list = itemSource[key];
                    if (!list.Contains(val))
                    {
                        list.Add(val);
                        itemSource[key] = list;
                    }
                }
                else
                {
                    itemSource.Add(key, new List<string>() { val });
                }
            }
        }

        internal static void UpdateOutputReamak(object remark)
        {
            if (remark != null && !String.IsNullOrEmpty(remark.ToString()))
            {
                var itemSource = GlobalData.GetAllItemSource();
                string key = "OutputReamak";
                string val = remark?.ToString() ?? "";
                if (val.IsNullOrEmpty()) return;
                if (itemSource.Keys.Contains(key))
                {
                    var list = itemSource[key];
                    if (!list.Contains(val))
                    {
                        list.Add(val);
                        itemSource[key] = list;
                    }
                }
                else
                {
                    itemSource.Add(key, new List<string>() { val });
                }
            }
        }


        internal static void SetRemarkItemSource(System.Windows.Controls.ComboBox comboBox, bool isInput = false)
        {
            string key = isInput ? "InputReamak" : "OutputReamak";
            var itemSource = GlobalData.GetAllItemSource();
            if (itemSource == null || comboBox == null) return;
            if (itemSource.Keys.Contains(key))
            {
                var list = itemSource[key];
                comboBox.ItemsSource = null;
                comboBox.ItemsSource = list;
            }
        }

        /// <summary>
        /// 将派车单的信息同步到当前的磅单
        /// </summary>
        /// <param name="send">派车单</param>
        /// <param name="weighingBill">磅单</param>
        public static void SendCardMargeToWeighing(SendCarBill send, ref WeighingBill weighingBill)
        {
            weighingBill.sendCarBillId = send.id;
            weighingBill.sendCarBillNumber = send.number;
            // weighingBill.send = send.UserName;
            weighingBill.sendCompanyId = send.sendCompanyId;
            weighingBill.sendCompanyName = send.sendCompanyName;
            weighingBill.sendYardId = send.sendYardId;
            weighingBill.sendYardName = send.sendYardName;
            weighingBill.receiveCompanyId = send.receiveCompanyId;
            weighingBill.receiveCompanyName = send.receiveCompanyName;
            weighingBill.receiveYardId = send.receiveYardId;
            weighingBill.receiveYardName = send.receiveYardName;
            weighingBill.materialId = send.materialId;
            weighingBill.materialName = send.materialName;
            weighingBill.carId = send.carId;
            weighingBill.carNumber = send.carNumber;
            weighingBill.driver = send.driver;
            weighingBill.driverMobile = send.driverMobile;
            weighingBill.remark = send.remark;
        }

        /// <summary>
        /// 将当前的磅单的信息同步到派车单
        /// </summary>
        /// <param name="weighingBill">磅单</param>
        /// <param name="sendCarBill">派车单</param>
        public static void WeighingMargeToSendCarrBill(WeighingBill weighingBill, ref SendCarBill sendCarBill)
        {
            sendCarBill.inFactoryTime = weighingBill.inTime;
            sendCarBill.outFactoryTime = weighingBill.outTime;
            sendCarBill.weighingNumber = weighingBill.number;
            sendCarBill.weighingBillId = weighingBill.id;
            sendCarBill.syncTime = DateTimeHelper.GetTimeStamp();
        }

        /// <summary>
        /// 首次保存
        /// </summary>
        /// <param name="localConfig"></param>
        /// <returns></returns>
        internal static int SaveAppConfig(LocalConfig localConfig)
        {
            App.Config = localConfig;
            return LocalConfigDao.Instance.InsertOrUpdate(localConfig);
        }

        /// <summary>
        /// 更新数据库存中的 配制信息
        /// </summary>
        internal static int UpdateAppConfig(string configName = "")
        {
            return ConfigDao.Instance.UpdateAppConfig(configName);
        }

        /// <summary>
        /// 保存成功  截图
        /// </summary>
        /// <param name="bill"></param>
        internal static void CaptureJpeg(string number, int status)
        {
            try
            {
                MainWindow? mw = System.Windows.Application.Current.MainWindow as MainWindow;
                mw?.VideoContent?.CaptureJpeg(number, status);
            }
            catch (Exception e)
            {
                Log.Error("截图失败：" + e.Message);
            }
        }


        /// <summary>
        /// 处理系统到期
        /// </summary>
        public static void Handleexpire()
        {
            if (App.Config.ActiveCode.IsNullOrEmpty() && App.Config.RadomKey.IsNullOrEmpty()) return;

            try
            {
                App.Config.RadomKey = "";
                App.Config.ActiveTime = null;
                App.Config.ActiveCode = "";
                UpdateAppConfig(null);

                File.Delete(Constant.ActiveCodeEncryptFile);
                System.Windows.Application.Current.MainWindow.ApplyTemplate();
                WindowCollection collection = System.Windows.Application.Current.MainWindow.OwnedWindows;
                foreach (HandyControl.Controls.Window item in collection)
                {
                    item.ApplyTemplate();
                }
            }
            catch (Exception ex)
            {
                Log.Error("处理系统到期出错:" + ex.Message);
                throw;
            }
        }
        public static void AlertInfo(string msg, System.Windows.Window? window = null)
        {
            MessageBox.Show(window, msg, "提示");
        }

        /// <summary>
        /// 询问 是否
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="window"></param>
        /// <returns></returns>
        public static MessageBoxResult Ask(string msg, System.Windows.Window? window = null)
        {
            return MessageBox.Show(window, msg, "询问", MessageBoxButton.YesNo);
        }


        #region 语音


        /// <summary>
        /// 语音
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="isCancelAll">是否取消之前未完成的</param>
        public static void SpeakAsync(string msg, bool isCancelAll = false)
        {
            if (!App.Config.FunctionConfig.Speak) return;
            if (!msg.IsNullOrEmpty())
            {
                try
                {
                    SpVoice Voice = new()
                    {
                        Volume = 80
                    };

                    if (isCancelAll)
                    {
                        // SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak
                        Voice.Speak(msg, SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
                    }
                    else
                    {
                        Voice.Speak(msg, SpeechVoiceSpeakFlags.SVSFDefault);
                    }
                }
                catch (Exception)
                {
                }
            }
        }


        #endregion

        /// <summary>
        /// 清除表所有的业务数据
        /// <param name="isContainsUser">是否包含用户数据</param>
        /// </summary>
        public static void ClearUseData(bool isContainsUser = false)
        {
            CommonDao.Instance.ClearUserData(isContainsUser);
        }

        #region 创建桌面快捷方式

        public static void CreateShortcat(string targetPath = "")
        {
            if (targetPath.IsNullOrEmpty())
            {
                targetPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            }

            string dirPath = Environment.CurrentDirectory;
            string exePath = Assembly.GetExecutingAssembly().Location;
            string iconName = "favicon.ico";
            string iconPath = Path.Combine(dirPath, iconName);
            string name = GetShortcatName() + ".lnk";
            string shortFile = Path.Combine(targetPath, name);
            if (exePath.EndsWith(".dll"))
            {
                exePath = exePath.Substring(0, exePath.Length - 4) + ".exe";
            }
            if (!File.Exists(shortFile))
            {
                WshShell shell = new WshShell();
                IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortFile);
                shortcut.TargetPath = @exePath;          //目标文件
                shortcut.WorkingDirectory = dirPath;    //目标文件夹
                shortcut.WindowStyle = 1;               //目标应用程序的窗口状态分为普通、最大化、最小化【1,3,7】
                shortcut.Description = "称重管理系统";   //描述
                shortcut.IconLocation = iconPath;  //快捷方式图标
                shortcut.Arguments = "";
                shortcut.Hotkey = "SHIFT+DELETE";    // 快捷键
                shortcut.Save();
            }
            else
            {
                Console.WriteLine("桌面快捷方式Exists");
            }
        }
        /// <summary>
        /// 桌面快捷方式名称
        /// </summary>
        /// <returns></returns>
        public static string GetShortcatName()
        {
            string res = "称重系统";
            return res;
        }
        /// <summary>
        /// 设置开机自动启动
        /// </summary>
        /// <param name="onOff">自启开关</param>
        public static void SetAutoStart(bool onOff = true)
        {
            var systemStartPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            string name = "称重系统.lnk";
            string shortFile = Path.Combine(systemStartPath, name);
            if (onOff)//开机启动
            {
                if (!File.Exists(shortFile))
                {
                    CreateShortcat(systemStartPath);
                }
            }
            else
            {
                if (File.Exists(shortFile))
                {
                    File.Delete(shortFile);
                }
            }
        }
        #endregion


        #region 模拟过磅

        /// <summary>
        /// 模拟过磅
        /// </summary>
        /// <param name="type">过磅类型</param>
        /// <param name="isOut">是否出场</param>
        /// <returns></returns>
        public static double RandomTonner(WeightingBillType type, bool isOut)
        {
            //以千克外传
            var v = Math.Round(new Random().NextDouble() * 1000, 0);
            double result;
            if (type == WeightingBillType.Buy)
            {
                result = isOut ? 10000 + v : 50000 + v;
            }
            else
            {
                result = isOut ? 50000 + v : 10000 + v;
            }
            return result;
        }

        /// <summary>
        /// 简易 模拟过磅
        /// </summary>
        /// <param name="isbig">是否需要一个大的吨位</param>
        /// <returns></returns>
        public static double RandomTonner(bool isbig)
        {
            //以千克外传
            var v = Math.Round(new Random().NextDouble() * 1000, 0);
            double result = isbig ? (50000 + v) : (10000 + v); ;
            return result;
        }

        public static void SetTonner(double tonner)
        {
            if (App.Config.WeighingConfig.Unit == Unit.Tone)
            {
                tonner = Math.Round(tonner / 1000, App.Config.WeighingConfig.Digits, MidpointRounding.AwayFromZero);
            }
            var mw = App.Current.MainWindow as MainWindow;

            mw?.ScaleContentUc?.ChangeActiveScaleDataContent(nameof(ScaleVo.Tonner), tonner);
            mw?.ScaleContentUc?.ChangeActiveScaleDataContent(nameof(ScaleVo.Status), 1);
        }
        /// <summary>
        /// 单位必须相同
        /// </summary>
        /// <param name="scaleName"></param>
        /// <param name="tonner"></param>
        public static void SetTonner(string scaleName, double tonner)
        {
            var mw = App.Current.MainWindow as MainWindow;
            mw?.ScaleContentUc?.ChangeScaleDataContent(scaleName, nameof(ScaleVo.Tonner), tonner);
        }
        #endregion

        public static void UpdateScaleItemUnitText()
        {
            MainWindow? window = App.Current.MainWindow as MainWindow;
            ScaleContent? sc = window?.ScaleContentUc;
            WrapPanel? wp = sc?.Content as WrapPanel;
            if (wp?.Children.Count > 0)
            {
                foreach (ScaleItem item in wp.Children)
                {
                    item?.UpdateUnitText();
                }
            }

        }

        public static void ChangeVideoShow(CameraInfoVo vo)
        {
            MainWindow? window = App.Current.MainWindow as MainWindow;
            VideoContent? vc = window?.VideoContent;
            vc?.OnCameraChanged(vo);
        }


        public static bool HasPermision(string permissionKey)
        {
            if (App.CurrentUser == null) return false;
            //开发者
            if (App.CurrentUser.roleType == (int)UserRoleType.Developer) return true;
            //没有任何权限 collapsed
            if (App.CurrentUser.Permissions == null || App.CurrentUser.Permissions.Count <= 0) return false;
            //未传参
            if (string.IsNullOrEmpty(permissionKey)) return false;

            return UserDao.Instance.HasPermission(permissionKey);
        }


        public static void WeighingViewPricePanel()
        {
            MainWindow window = App.Current.MainWindow as MainWindow;
            if (window?.WeighingUIBorder.Child is NomalWeighingUc nouc)
            {
                nouc?.InputWeighingUc.ShowOrHidePricePanel();
                nouc?.outputWeighingUc.ShowOrHidePricePanel();
            }

        }

        public static void ClearLastRecognizePlate()
        {

        }

        public static string ConmunicationTypeText(int? conmunicationType)
        {
            switch ((ConmunitationType)conmunicationType)
            {
                case ConmunitationType.TcpIp:
                    return "TCPIP";
                case ConmunitationType.Rs232:
                    return "RS232 COM";
                case ConmunitationType.Rs485:
                    return "RS485 COM";
                default:
                    return "";
            }
        }


        #region 二维码

        /// <summary>
        /// 以阿里云OOS 地址生成二维码
        /// </summary>
        public static void ShowAliyunOosQrCode(Image image, string billNumber)
        {
            //try
            //{
            //    string fileName = billNumber + Constant.BillCaputureSuffix;
            //    string key = AliOOSHelper.Insance.GetKey(fileName);
            //    string url = AliOOSHelper.Insance.BuildRemoteUrl(key);
            //    var bitmap = MyHelper.QrCode.QrCodeHelper.GenerateQrCode(url, 90, 90);
            //    image.Source = BitmapHelper.ToBitmapImage(bitmap);
            //}
            //catch (Exception e)
            //{
            //    Log.Error("生成 阿里云OOS 地址生成二维码出错：" + e.Message);
            //}

        }

        /// <summary>
        /// 以磅单编号，生成和显示 二维码
        /// </summary>
        public static void ShowBillNumberQrCode(Image? image, String number)
        {
            if (image == null) return;
            if (number.IsNullOrEmpty() || number.Length < 8)
            {
                Log.Info("以磅单编号生成二维码时，磅单编号长度应超过8位");
                return;
            }
            var bitmap = MyHelper.QrCode.QrCodeHelper.GenerateQrCode(number, 90, 90);
            image.Source = BitmapHelper.ToBitmapImage(bitmap);
        }

        /// <summary>
        /// 以磅单编号，生成和显示 条码, 编号长度必须小于13
        /// </summary>
        public static void ShowBillNumberBarCode(Image? image, String number, int width = 120, int height = 30)
        {
            if (image == null) return;
            if (number.IsNullOrEmpty() || number.Length < 8)
            {
                Log.Info("以磅单编号生成条码时，磅单编号长度应超过8位");
                return;
            }
            var bitmap = MyHelper.QrCode.QrCodeHelper.GenerateBarCode(number, width, height);
            image.Source = BitmapHelper.ToBitmapImage(bitmap);
        }

        /// <summary>
        /// 生成和显示 二维码
        /// </summary>
        public static void ShowQrCode(Image image, String content)
        {
            if (image == null) return;
            if (!content.IsNullOrEmpty())
            {
                var bitmap = MyHelper.QrCode.QrCodeHelper.GenerateQrCode(content, 100, 100);
                image.Source = BitmapHelper.ToBitmapImage(bitmap);
            }
        }

        #endregion

        #region 根据二维码规则，获取二维码的真实值

        public static string GetQrContentByRules(QrContentVo contentVo, WeighingBill bill)
        {
            string ValueString = "";
            if (contentVo == null) return "";
            switch (contentVo.QrContentType)
            {
                case QrContentType.Number:
                    ValueString = bill.number;
                    break;
                case QrContentType.ImageUrl:
                    ValueString = contentVo.Url;
                    break;
                case QrContentType.Variables:
                    var rules = contentVo.Variables.Split("|");
                    var dic = ObjectToDict(bill, false, true);
                    foreach (var rule in rules)
                    {
                        if (dic.Keys.Contains(rule))
                        {
                            var v = dic[rule];
                            var curr = StringHelper.ContainsChinese(v) ? StringHelper.StringToHexString(v, null, false) : v;
                            ValueString += "|" + curr;
                        }
                    }
                    ValueString = ValueString.TrimStart('|');

                    break;
                case QrContentType.UrlAndVariables:

                    var rules2 = contentVo.Variables.Split("|");
                    var dic2 = ObjectToDict(bill, false, true);
                    foreach (var rule in rules2)
                    {
                        if (dic2.Keys.Contains(rule))
                        {
                            var k = rule.Substring(0, 1).ToLower() + rule.Substring(1);
                            var v = dic2[rule];
                            var curr = StringHelper.ContainsChinese(v) ? StringHelper.StringToHexString(v, Encoding.UTF8, false) : v;
                            ValueString += "&" + k + "=" + curr;
                        }
                    }
                    string param = contentVo.OtherParam;
                    if (!param.StartsWith('&'))
                    {
                        param = "&" + param;
                    }
                    ValueString = contentVo.Url + "?" + ValueString.TrimStart('&') + param;
                    break;
            }
            return ValueString.TrimStart('|');
        }

        #endregion
        public static int GetDaysInMonth(int year = 0, int month = 0)
        {
            if (year <= 0) year = DateTime.Now.Year;
            if (month <= 0) month = DateTime.Now.Month;
            int days = DateTime.DaysInMonth(year, month);
            return days;
        }

        public static string GetUnitText()
        {
            string u = App.Config.WeighingConfig.Unit == Unit.KG ? "千克" : "吨";
            return u;
        }

        public static string GetExceptionCodeLine(Exception ex)
        {
            if (ex != null)
            {
                try
                {
                    var line = ex?.StackTrace?.Substring(ex.StackTrace.IndexOf("行号"), ex.StackTrace.Length - ex.StackTrace.IndexOf("行号"));
                    return line ?? "行号 -1 ";
                }
                catch (Exception)
                {
                    return " 行号 -1 ";
                }
            }
            else
            {
                return "行号 0";
            }
        }
        /// <summary>
        /// show the icon file under root path, if not exist ,don't show
        /// </summary>
        public static void ShowCustomIcon(System.Windows.Window window)
        {
            string iconfile = Constant.CustomIconFile;
            if (File.Exists(iconfile) && window != null)
            {
                var img = BitmapHelper.FromString(iconfile);
                window.Icon = img;
            }
        }

        public static void ShowCustomNotiflyIco(HandyControl.Controls.NotifyIcon notifyIcon)
        {
            string iconfile = Constant.CustomIconFile;
            if (File.Exists(iconfile) && notifyIcon != null)
            {
                notifyIcon.Icon = BitmapHelper.FromString(iconfile);
            }
        }

        /// <summary>
        /// 内容是否符合 json 格式
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static bool IsJsonContent(string content)
        {
            return !string.IsNullOrEmpty(content) &&
                ((content.StartsWith("[") && content.EndsWith("]"))
                || (content.StartsWith("{") && content.EndsWith("}")));
        }

        /// <summary>
        /// 指定的打印机
        /// </summary>
        /// <param name="printType"></param>
        /// <returns>PrintQueue Or Null </returns>
        public static PrintQueue? GetPrintQueue(WeightingBillType printType)
        {
            if (App.Config.BillPrintConfig.AllUserDefaultPrinter)
            {
                return LocalPrintServer.GetDefaultPrintQueue();
            }

            var lps = new LocalPrintServer();
            var ps = lps.GetPrintQueues();

            if (printType == WeightingBillType.WeighintBill)
            {
                PrintQueue? result = null;
                foreach (var pq in ps)
                {
                    if (pq.FullName == App.Config.BillPrintConfig.WeighingBillPrinterName)
                    {
                        result = pq;
                        break;
                    }
                }
                result ??= LocalPrintServer.GetDefaultPrintQueue();
                return result;
            }
            else
            {
                PrintQueue? result = null;
                string name = string.Empty;
                switch (printType)
                {
                    case WeightingBillType.ExitSlip:
                        name = App.Config.BillPrintConfig.ExitSlipPrinterName;
                        break;
                    case WeightingBillType.LoadingBill:
                        name = App.Config.BillPrintConfig.LoadBillPrinterName;
                        break;
                    case WeightingBillType.UnLoadingBill:
                        name = App.Config.BillPrintConfig.UnLoadBillPrinterName;
                        break;
                    case WeightingBillType.WeighintBill:
                        name = App.Config.BillPrintConfig.WeighingBillPrinterName;
                        break;
                    default:
                        break;
                }
                if (name.IsNullOrEmpty())
                {
                    result = null;
                }
                else
                {
                    foreach (var pq in ps)
                    {
                        if (pq.FullName.Equals(name))
                        {
                            result = pq;
                            break;
                        }
                    }
                }
                return result;
            }
        }



        public static void MoveCursorToLast(System.Windows.Controls.ComboBox comboBox, int start)
        {
            if (start <= 0) return;
            int len = 0;
            string name = "PART_EditableTextBox";
            Grid? grid = comboBox.Template.LoadContent() as Grid;
            System.Windows.Controls.TextBox? tb = grid?.FindName(name) as System.Windows.Controls.TextBox;

            var methodd = tb?.GetType()
                 .GetMethod("Select", BindingFlags.Instance | BindingFlags.Public);
            methodd?.Invoke(tb, new object[] { start, len });

        }

        public static Dictionary<string, string> GetHeaderDic(System.Windows.Controls.DataGrid dataGrid, bool excludeHider = false)
        {
            var headerDic = new Dictionary<string, string>();
            if (dataGrid == null) return headerDic;
            foreach (var column in dataGrid.Columns)
            {
                if (excludeHider == true)
                {
                    if (column is DataGridTextColumn textColumn && column.Visibility == Visibility.Visible)
                    {
                        var binding = textColumn.Binding as System.Windows.Data.Binding;
                        var key = binding?.Path.Path ?? "";
                        var val = textColumn.Header.ToString();
                        headerDic.Add(key, val ?? "");
                    }
                }
                else
                {
                    if (column is DataGridTextColumn textColumn)
                    {
                        var binding = textColumn.Binding as System.Windows.Data.Binding;
                        var key = binding?.Path.Path ?? "";
                        var val = textColumn.Header.ToString();
                        headerDic.Add(key, val ?? "");
                    }
                }
            }
            return headerDic;
        }

        /// <summary>
        ///  将对像转化成字典
        /// </summary>
        /// <param name="obj">对像</param>
        /// <param name="isProperty">使用属性作为Key，否则 ，使用 字段作为Key</param>
        /// <param name="isBigCamal">Key 是否 为大驼峰</param>
        /// <returns></returns>
        public static Dictionary<string, string> ObjectToDict(Object obj, bool isProperty = false, bool isBigCamal = false)
        {

            var dictionary = new Dictionary<string, string>();
            if (isProperty)
            {
                // var properties = obj.GetType().GetProperties(BindingFlags.Public);
                var properties = obj.GetType().GetProperties();
                foreach (var p in properties)
                {
                    var key = isBigCamal == false ? StringHelper.LowerCaseFirstLetter(p.Name) : p.Name;
                    var value = p.GetValue(obj);
                    if (value is DateTime dateTimeValue)
                    {
                        // Format DateTime properties as "yyyy-MM-dd HH:mm:ss"
                        dictionary[key] = dateTimeValue.ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    else if (value != null)
                    {
                        dictionary[key] = value?.ToString() ?? "";
                    }
                    else
                    {
                        dictionary[key] = "";
                    }
                }
            }
            else
            {
                var fields = obj.GetType().GetFields();
                foreach (var field in fields)
                {
                    var key = isBigCamal ? StringHelper.UpperCaseFirstLetter(field.Name) : field.Name;
                    var value = field.GetValue(obj);
                    if (value is DateTime dateTimeValue)
                    {
                        // Format DateTime properties as "yyyy-MM-dd HH:mm:ss"
                        dictionary[key] = dateTimeValue.ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    else if (value != null)
                    {
                        dictionary[key] = value?.ToString() ?? "";
                    }
                    else
                    {
                        dictionary[key] = "";
                    }
                }
            }
            return dictionary;
        }
        internal static string GetWeighungTypeText(WeightingBillType billType)
        {
            var res = "";
            switch (billType)
            {
                case WeightingBillType.Otrher:
                    res = "其它";
                    break;
                case WeightingBillType.Buy:
                    res = "采购";
                    break;
                case WeightingBillType.Sale:
                    res = "销售";
                    break;
                case WeightingBillType.Self:
                    res = "内倒";
                    break;
                case WeightingBillType.Foreign:
                    res = "外来";
                    break;
                case WeightingBillType.Mixture:
                    res = "过磅";
                    break;
                case WeightingBillType.UNKNOWN:
                    break;
                case WeightingBillType.ExitSlip:
                    break;
                case WeightingBillType.LoadingBill:
                    break;
                case WeightingBillType.UnLoadingBill:
                    break;
                case WeightingBillType.WeighintBill:
                    break;
                default:
                    break;
            }
            return res;
        }

        /// <summary>
        /// 获取EXCL 自定义 Title 和 字段名称的 字典
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, string> GetBillTitleFieldNameDic()
        {
            Dictionary<string, string> dic = new();
            try
            {
                Type type = typeof(WeighingBill);
                var fields = type.GetFields().Where((f) =>
                {
                    var attr = f.GetCustomAttribute(typeof(WeighingBillAttribute));
                    return attr != null;
                });
                foreach (var field in fields)
                {
                    if (field.GetCustomAttribute(typeof(WeighingBillAttribute)) is WeighingBillAttribute attr)
                    {
                        dic.Add(attr.Title, field.Name);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("GetBillTitlePropertyDic :" + ex.Message);
            }
            return dic;
        }

        /// <summary>
        ///获取打印时间字符串 
        /// </summary>
        /// <param name="vo">磅单视图</param>
        /// <returns></returns>

        public static string GetPrintTimeStr(WeighingBillVo? vo)
        {
            if (vo == null) return DateTimeHelper.getCurrentDateTime();
            return App.Config.BillPrintConfig.PrintTimeType switch
            {
                PrintTimeType.PrintDateTime => DateTimeHelper.getCurrentDateTime(),
                PrintTimeType.PrintTime => DateTimeHelper.getCurrentDateTime(Constant.TimeFormat),
                PrintTimeType.PrintDate => DateTimeHelper.getCurrentDateTime(Constant.DateFormat),
                PrintTimeType.InDateTime => (vo?.InTime ?? DateTime.Now).ToString(Constant.DateTimeFormat),
                PrintTimeType.InDate => (vo?.InTime ?? DateTime.Now).ToString(Constant.DateFormat),
                PrintTimeType.InTime => (vo?.InTime ?? DateTime.Now).ToString(Constant.TimeFormat),
                PrintTimeType.OutDateTime => (vo?.OutTime ?? DateTime.Now).ToString(Constant.DateTimeFormat),
                PrintTimeType.OutDate => (vo?.OutTime ?? DateTime.Now).ToString(Constant.DateFormat),
                PrintTimeType.OutTime => (vo?.OutTime ?? DateTime.Now).ToString(Constant.TimeFormat),
                _ => DateTimeHelper.getCurrentDateTime(),
            };
        }

        /// <summary>
        ///获取磅单抬头
        /// </summary>
        /// <param name="vo">磅单视图</param>
        /// <returns></returns>
        public static string GetBillTitle(WeighingBillVo? vo)
        {
            if (vo == null) return "过磅单";
            string temp = "XXXX 公司";
            return App.Config.BillPrintConfig.BillTitleType switch
            {
                DefaultBillTitleType.UseCompanyFullName => App.CurrentCompanyVo?.FullName ?? "使用" + temp,
                DefaultBillTitleType.SendCompanyFullName => vo.SendCompanyName ?? "发货" + temp,
                DefaultBillTitleType.ReceivedCompanyFullName => vo.ReceiveCompanyName ?? "收货" + temp,
                DefaultBillTitleType.TransCompanyFullName => vo.TranceCompanyName ?? "运输" + temp,
                DefaultBillTitleType.FixText => App.Config.BillPrintConfig.FiexTitle,
                _ => App.CurrentCompanyVo?.FullName ?? temp,
            };
        }

    }
}
